<template>
    <f7-page>
        <f7-navbar>
            <f7-nav-left>
                <f7-link  @click="back">
                    <f7-icon icon="icon-back" style="margin-left: 15px;"></f7-icon>
                </f7-link>
            </f7-nav-left>
            <f7-nav-title title="问题复验"></f7-nav-title>
            <f7-nav-right>
                <f7-badge color="orange">待复验</f7-badge>&nbsp;&nbsp;
                <f7-badge color="pink" v-if="timeout()">超时</f7-badge>
            </f7-nav-right>
        </f7-navbar>
        <f7-list inline-labels no-hairlines no-hairlines-between inset>
        	<f7-list-item v-if="checkQualityProblem.bidSectionId != null">
                <f7-label style="width:30%;">标段</f7-label>
                <f7-list-item-cell> 
                {{ $store.state.global.bidSectionMap[checkQualityProblem.bidSectionId].bid_section_name + '(' + $store.state.global.projectMap[$store.state.global.bidSectionMap[checkQualityProblem.bidSectionId].project_id].project_name + ')' }}
            	</f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">部位</f7-label>
                <f7-list-item-cell>
                    <f7-row>
                        <f7-col width="70">{{checkQualityProblem.place}}</f7-col>
                        <f7-col width="30" v-if="checkQualityProblem.roomId != null"
                             @click.stop="openHousePoint(checkQualityProblem.roomId)">
                            <f7-badge color="blue">图</f7-badge>
                        </f7-col>
                    </f7-row>
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">检查项</f7-label>
                <f7-list-item-cell>
                    {{$store.state.global.problemClassMap[$store.state.global.problemClassMap[checkQualityProblem.problemClassId].parent_problem_class_id].problem_class_name
                    + ' - ' +
                    $store.state.global.problemClassMap[checkQualityProblem.problemClassId].problem_class_name}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">描述</f7-label>
                <f7-list-item-cell>
                    <f7-row v-if="checkQualityProblem.problemId != null">
                        {{$store.state.global.problemMap[checkQualityProblem.problemId].problem_name}}
                    </f7-row>
                    <f7-row>
                        {{checkQualityProblem.remark}}
                    </f7-row>
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">问题照片</f7-label>
               	<f7-list-item-cell>
                    <img width="80" height="80" style="margin-right: 5px;"
                         v-for="(imageFile, i) in checkQualityProblem.imageFile"
                         :src="imageFile.url" @click="$refs.imageFile.open(i)">
                    </img>
                </f7-list-item-cell>
                <f7-photo-browser :photos="checkQualityProblem.imageFile"
                                  type="popup" ref="imageFile" back-link-text="关闭">
                </f7-photo-browser>
            </f7-list-item>
            <f7-list-item v-if="checkQualityProblem.registBy != null">
                <f7-label style="width:30%;">提交人</f7-label>
                <f7-list-item-cell>
                    {{$store.state.global.userMap[checkQualityProblem.registBy].realname}}&nbsp;
                    {{formateDate(checkQualityProblem.registDate)}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">整改期限</f7-label>
                <f7-list-item-cell>
                    {{formateDate(checkQualityProblem.repairDeadline)}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item v-if="checkQualityProblem.repair != null">
                <f7-label style="width:30%;">整改人</f7-label>
                <f7-list-item-cell>
                    {{$store.state.global.userMap[checkQualityProblem.repair].realname}}&nbsp;
                    {{formateDate(checkQualityProblem.repairDate)}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">整改照片</f7-label>
               	<f7-list-item-cell>
                    <img width="80" height="80" style="margin-right: 5px;"
                         v-for="(imageFile, i) in checkQualityProblem.repairImageFile"
                         :src="imageFile.url" @click="$refs.repairImageFile.open(i)">
                    </img>
                </f7-list-item-cell>
                <f7-photo-browser :photos="checkQualityProblem.repairImageFile"
                                  type="popup" ref="repairImageFile" back-link-text="关闭">
                </f7-photo-browser>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">整改说明</f7-label>
                <f7-list-item-cell>
                    {{checkQualityProblem.repairRemark}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item v-if="checkQualityProblem.contractorId != null">
                <f7-label style="width:30%;">责任单位</f7-label>
                <f7-list-item-cell>
                    {{$store.state.global.contractorMap[checkQualityProblem.contractorId].contractor_short_name}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item v-if="checkQualityProblem.reinspect.length != 0">
                <f7-label style="width:30%;">复验人</f7-label>
                <f7-list-item-cell>
                <span v-for="(user, i) in checkQualityProblem.reinspect" style="margin-right:4px;">
                    {{$store.state.global.userMap[user].realname}}
                </span>
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item  v-if="isReinspectUser()">
                <TakePhoto ref="refTakePhoto" @photoAdd="photoAdd" @photoDelete="photoDelete"></TakePhoto>
            </f7-list-item>
            <f7-list-item v-if="isReinspectUser()">
                <f7-input type="textarea" label="复验说明" placeholder="复验补充说明"
                          :value="form.remark" @change="form.remark = $event.target.value">
                </f7-input>
            </f7-list-item>
            <f7-list-item  v-if="checkQualityProblem.ccs.length != 0">
                <f7-label style="width:30%;">抄送人</f7-label>
                <f7-list-item-cell>
                <span v-for="(user, i) in checkQualityProblem.ccs" style="margin-right:4px;">
                    {{$store.state.global.userMap[user].realname}}
                </span>
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item v-if="isReinspectUser()">
            	<f7-list-item-cell>
                    <f7-button big round @click="saveTemporary()">暂存</f7-button>
                </f7-list-item-cell>
                <f7-list-item-cell v-show="isOnline">
                    <f7-button big round @click="ensureSubmit()">通过</f7-button>
                </f7-list-item-cell>
                <f7-list-item-cell>
                    <f7-button big round fill color="red" @click="sendBack()">退回</f7-button>
                </f7-list-item-cell>
            </f7-list-item>
        </f7-list>
    </f7-page>
</template>

<script>
// import $ from 'jquery';
import networkEvent from '@/mixins/networkEvent';
import back from '@/mixins/back.js';
import Common from "@/utils/Common.js";
import DateUtil from "@/utils/DateUtil.js";
import FileUtil from "@/utils/FileUtil.js";
import events from 'events';
import eventBus from '@/utils/eventBus.js';
import store from '@/store';
import {getUser, setUser, clearUser} from '@/utils/auth';
import {getStore, setStore, clearStore} from '@/utils/storage';
import keys from '@/utils/rememberKeys';
import request from '@/utils/request';
import db from '@/utils/db';
import TakePhoto from "@/components/TakePhoto.vue";
import { upload, uploadImage } from '@/utils/upload';
export default {
    store: store,
    components: {
        TakePhoto,
	},
	mixins: [networkEvent, back],
    props: {
    	checkQualityProblem: {
    		type: Object
    	},
    	module: {
    		type: String
    	}
    },
    data: function() {
    	return {
    		form: {
    			tid: null,
    			checkQualityProblemId: null,
                photos: [],
                remark: '',
                reinspect: {
                    userId: '',
                }
            },
            deletePhotos: []
    	};
    },
    methods: {
        timeout: function() {
            try {
                var deadline = this.checkQualityProblem.repairDeadline;
                var repairDate = this.checkQualityProblem.repairDate;
                if(repairDate > deadline) {
                    return true;
                }
            } catch(e) {}
            return false;
        },
        formateDate: function(problem) {
            var date = '';
            if(problem != null) {
            	date += DateUtil.dateToStr('yyyy-MM-dd HH:mm', problem) + ' ';
            }
            return date;
        },
        photoAdd: function(cdvPath) {
    		this.form.photos.push(cdvPath);
    	},
    	photoDelete: function(cdvPath) {
    		for(var i = 0; i < this.form.photos.length; i++) {
    			if(cdvPath == this.form.photos[i]) {
    				this.form.photos.splice(i, 1);
                    if(cdvPath.indexOf('localeCheck') > -1) {
                        this.deletePhotos.push(cdvPath);
                    }
    				break;
    			}
    		}
    	},
        openHousePoint: function(houseId) {
            var self = this;
            var house = this.$store.state.global.houseMap[houseId];
            var houseType = null;
            if(house != null) {
            	var houseType = this.$store.state.global.houseTypeMap[house.house_type_id];
            } else {
            	var houseType = this.$store.state.global.houseTypeMap[self.checkQualityProblem.houseTypeId];
            }
            var router = self.$f7router.navigate('/HousePoint', {
                props: {
                    imageUrl: houseType.url,
                    pointCount: 20,
                    initialPoints: self.checkQualityProblem.problemValues,
                    editable: false
                }
            });
    	},
    	isReinspectUser: function() {
            var currentUserId = getUser().userId;
            for(var i = 0; i < this.checkQualityProblem.reinspect.length; i++) {
                var user = this.checkQualityProblem.reinspect[i];
                if(user == currentUserId) {
                    return true;
                }
            }
            return false;
        },
        ensureSubmit: function(){
            var self = this;
            this.$f7.dialog.confirm("您确定通过？","",function () {
                self.submit();
            });
        },
        submit: function() {
			var self = this;
			self.$f7.preloader.show();
			let dialog = self.$f7.dialog.progress('上传图片中', 0);
			dialog.finishCount = 0;
			let data = {
				checkQualityProblemId: self.checkQualityProblem.id,
				reinspectUserId: getUser().userId,
				reinspectRemark: self.form.remark,
				photos: []
			};
			let promises = [];
			self.form.photos.forEach(photoPath => {
				let promise = FileUtil.read(photoPath, 'image/jpeg').then(blob => {
					let splits = photoPath.split("/");
					let filename = splits[splits.length - 1];
					return uploadImage(filename, blob);
				}).then(result => {
					data.photos.push(result.url);
					dialog.finishCount++;
					dialog.setProgress(parseInt(dialog.finishCount / (self.form.photos.length + 1)) * 100);
					return Promise.resolve();
				});
				promises.push(promise);
			});
			Promise.all(promises).then(() => {
				return request({
					url: '/api/checkQualityProblem/problemReinspect',
					method: 'post',
					data: data,
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					} //参数不能太复杂，数组只能是一维数组
				});
			}).then(result => {
				dialog.close();
				self.$f7.dialog.alert(result.detail.msg, '问题复验成功！');
				self.$f7router.back();
				// 同步工作台数据 self.$f7router.emit('updateSubmitProblem', result.element);
				self.$f7router.emit('problemStautsChange', result.element);
				if (self.form.tid != null) {
					self.$f7router.emit('deleteProblemReinspect', self.form.tid);
				}
				self.$f7.preloader.hide();
			}).catch(error => {
				dialog.close();
				self.$f7.dialog.alert('', '问题复验失败！');
				self.saveTemporary();
				console.error(error);
			});
        },
        sendBack: function() {
        	var self = this;
        	let sql = "\
    	        select * from offline_local_check_sendBack \
    	        where problem_id = '" + self.checkQualityProblem.id + "' \
    	    ";
        	Common.executeSql(sql, []).then((result) => {
				let rs = result.rs;
				let problemSendBack = {
					photos: []
				};
				if(rs.rows.length != 0) {
					let row = rs.rows.item(0);
	    			let photo = Common.strToJson(row.offline_sendBack_image_file);
	    			problemSendBack.photos.push(photo);
	    			problemSendBack.tid = row.tid;
	    			problemSendBack.remark = row.offline_sendBack_remark;
	    			problemSendBack.backReasonValue = row.back_reason_value;
				}
				var router = null;
				if(self.module == 'workbench') {
	        		router = this.$f7router.navigate('/SendBack', {
	                    props: {
	                    	problemId: self.checkQualityProblem.id,
	                    	module: 'localeCheck',
	                    	submitUrl: '/api/checkQualityProblem/problemSendBack',
	                    	backUrl: '/WorkbenchLocaleCheckMain',
	                    	updateable: true,
	                    	updateProblemApi: 'updateSubmitProblem',
	                    	problemSendBack: problemSendBack
	                    }
	                });
	        	} else if (self.module == 'unprocess') {
	        		router = this.$f7router.navigate('/SendBack', {
	                    props: {
	                    	problemId: self.checkQualityProblem.id,
	                    	module: 'localeCheck',
	                    	submitUrl: '/api/checkQualityProblem/problemSendBack',
	                    	backUrl: '/UnprocessedLocalCheckMain/',
	                    	updateable: true,
	                    	updateProblemApi: 'problemStautsChange',
	                    	problemSendBack: problemSendBack
	                    }
	                });
	        	}
				router.off('saveTemporaryProblemSendBack');
                router.on('saveTemporaryProblemSendBack', function(form) {
                	let sql = "";
            		if(form.tid == null) {
                        sql = "\
                            insert into offline_local_check_sendBack( \
                            problem_id, offline_sendBack_image_file, \
                            offline_sendBack_remark, \
                            back_reason_value) \
                            values (?, ?, ?, ?) \
                        ";  
                    } else {
                        sql = "\
                            update offline_local_check_sendBack \
                            set problem_id = ?, offline_sendBack_image_file = ?, \
                            offline_sendBack_remark = ?, \
            	            back_reason_value = ? \
                            where tid = '" + form.tid + "' \
                        ";
                    }
            		let values = [
            			form.problemId,
            			JSON.stringify(form.photos),
            			form.remark,
            			form.backReasonValue
            		];
            		Common.executeSql(sql, values).then((result) => {
            			self.$f7.dialog.alert('', '暂存问题成功！');
            		}).catch(error => {
            			console.error(error);
            			self.$f7.dialog.alert('', '暂存问题失败！');
            		});
                });
        	})
        	
        	
        },
        saveTemporary: function() {
			var self = this;
			self.$f7.preloader.show();
			let promises = [];
			self.deletePhotos.forEach(photo => {
				let promise = FileUtil.remove(photo).then(() => {
					return Promise.resolve();
				}).catch((error) => {
					console.error(error);
					return Promise.resolve();
				});
				promises.push(promise);
			});
			Promise.all(promises).then(() => {
				let promises = [];
				self.form.photos.forEach(photo => {
					let promise = null;
					if (photo.indexOf(Common.directory().localeCheck) < 0) {
						let splits = photo.split('/');
						let filename = splits[splits.length - 1];
						let to = Common.directory().base + Common.directory().localeCheck + filename;
						promise = FileUtil.copy(photo, to);
					} else {
						promise = new Promise((resolve, reject) => {
							resolve(photo);
						});
					}
					promises.push(promise);
				});
				return Promise.all(promises);
			}).then((paths) => {
				let photos = [];
				paths.forEach(path => {
					photos.push(path);
				});
				self.form.photos = photos;
				self.form.checkQualityProblemId = self.checkQualityProblem.id;
				let sql = '';
				if (self.form.tid == null) {
					sql =
						"\
							insert into offline_local_check_reinspect( \
							checkquality_problem_id, offline_reinspect_image_file, \
							offline_reinspect_remark) \
							values (?, ?, ?) \
						";
				} else {
					sql =
						"\
						update offline_local_check_reinspect \
						set checkquality_problem_id = ?, offline_reinspect_image_file = ?, \
						offline_reinspect_remark = ? \
						where tid = '" +
						self.form.tid + "'";
				}
				var values = [
					self.form.checkQualityProblemId,
					JSON.stringify(self.form.photos),
					self.form.remark
				];
				return Common.executeSql(sql, values);
			}).then((result) => {
				self.$f7.dialog.alert('', '暂存问题成功');
				let rs = result.rs;
				self.$f7router.emit('saveTemporary', self.form.tid || rs.insertId);
				self.$f7.preloader.hide();
				self.$f7router.back();
			}).catch(error => {
				console.error(error);
				self.$f7.dialog.alert('', '暂存问题失败');
				self.$f7.preloader.hide();
			});

		}
    },
    computed: {
    	
    },
    watch: {
    	
    },
    created: function() {
    	
    },
    mounted: function() {
    	var self = this;
        var currentUserId = getUser().userId;
        for(var i = 0; i < this.checkQualityProblem.reinspect.length; i++) {
        	var reinspectUser = self.checkQualityProblem.reinspect;
            if(reinspectUser[i] == currentUserId) {
            	window.parent.db.transaction(function(tx){
            		var sql = "\
            	        select * from offline_local_check_reinspect \
            	        where checkquality_problem_id = '" + self.checkQualityProblem.id + "' \
            	    ";
            		tx.executeSql(sql, [], function(tx, rs) {
            			if(rs.rows.length != 0) {
            				var row = rs.rows.item(0);
                			self.form.photos = Common.strToJson(row.offline_reinspect_image_file);
                        	self.$refs.refTakePhoto.addPhotos(self.form.photos);
                        	self.form.remark = row.offline_reinspect_remark;
                        	self.form.tid = row.tid;
            			}
            		});
            	}, function(error) {
            		console.error(error);
            	});
            }
        }
    }
}
</script>

<style scoped>

</style>